package sudoku.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;

import javax.swing.AbstractButton;
import javax.swing.JComboBox;

import language.Messages;

import utils.Pair;

public class ListenerGui implements ActionListener
{

	private Hashtable<AbstractButton, IController>	componentControllerMap;
	private Pair<JComboBox, IController>						combox;

	public ListenerGui() {
		componentControllerMap = new Hashtable<AbstractButton, IController>();
		combox = new Pair<JComboBox, IController>();
	}

	public void associate(JComboBox combox, IController controller)
	{
		combox.addActionListener(this);
		combox.addItem("");
		combox.addItem(Messages.languajes[0]);
		combox.addItem(Messages.languajes[1]);
		this.combox.setFirstElem(combox);
		this.combox.setSecondElem(controller);
	}

	public void associate(AbstractButton button, IController controller)
	{
		button.addActionListener(this);
		componentControllerMap.put(button, controller);
	}

	@Override
	public void actionPerformed(ActionEvent e)
	{
		IController controller = componentControllerMap.get(e.getSource());
		if (null == controller) {
			try {
				controller = combox.getSecondElem();
				JComboBox itemSelected = (JComboBox) e.getSource();
				String itemS;
				if (itemSelected != null) {
					itemS = (String) itemSelected.getSelectedItem();
					controller.process(itemS);
				}
			} catch (Exception e2) {
			}

		} else {
			controller.process(e.getActionCommand());
		}
	}
}
